package com.victor.common.core.utils;

import cn.hutool.extra.ftp.Ftp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPReply;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;


@Slf4j
public class FtpUtil {
    /**
     *
     * @param remotePath
     * @param uploadFilePath
     * @param host
     * @param port
     * @param userName
     * @param password
     * @param maxSizeMb
     * @return
     */
    public static boolean upload(String remotePath, String uploadFilePath, String host, String port, String userName, String password,Integer maxSizeMb, boolean passiveMode) {

        log.info("上传路径：" + remotePath + "+" + "文件路径：" + uploadFilePath);
        File file = new File(uploadFilePath);
        if (!file.exists()) {
            throw new RuntimeException("文件不存在");
        } else {

            Double sizeMb = new BigDecimal(file.length()).divide(new BigDecimal((1024 * 1024))).setScale(3, RoundingMode.HALF_UP).doubleValue();

            if (maxSizeMb>0 && sizeMb - maxSizeMb > 0) {

                throw new RuntimeException("文件超过"+maxSizeMb+"MB,上传失败!");
            }

            Ftp ftp = null;

            try {

                ftp = new Ftp(host, Integer.valueOf(port), userName, password);

                //开启服务器对UTF-8的支持，如果服务器支持就用UTF-8编码，否则就用本地编码（ISO-8859-1）
                if (FTPReply.isPositiveCompletion(ftp.getClient().sendCommand("OPTS UTF8", "ON"))) {
                    ftp.getClient().setControlEncoding("UTF-8");
                } else {
                    //FTP协议里面，规定文件名编码为iso-8859-1
                    ftp.getClient().setControlEncoding("ISO-8859-1");
                }
                if (passiveMode) {
                    ftp.getClient().enterLocalPassiveMode();
                }
                return ftp.upload(remotePath, file);

            } catch (Exception e) {

                log.error("FTP错误",e);

                if (e.getMessage().contains("Connection refused")) {
                    throw new RuntimeException("连接Ftp服务器失败，请检查通信地址或端口是否异常。");
                } else if (e.getMessage().contains("Login failed for")) {
                    throw new RuntimeException("Ftp账号或密码错误。");
                }
                throw new RuntimeException("Ftp连接出现错误，请排查原因。");
            } finally {
                try {
                    if (ftp != null) {
                        ftp.close();
                    }
                } catch (Exception e) {
                    throw new RuntimeException("关闭ftp连接失败", e);
                }
            }
        }
    }

    public static void main(String[] args) {
      try {

          boolean success= upload("/upload/", "C:\\Users\\zy\\Desktop\\HOW TO BACK FILES.txt", "192.168.0.65", "21", "dev02", "123456",20, false);
          System.out.println(success);
      } catch (Exception e) {
          e.printStackTrace();
      }

    }

}
